const CartHttp = require("../../models/cartHttp")
Page({
  data: {
    carts: [],
    allChecked: "",
    sum:""
  },
  async onLoad() {
    var res = await CartHttp.getCart();
    var allChecked = res.data.every(item => {
      return item.isSelected
    })
    console.log(allChecked)
    this.setData({
      carts: res.data,
      allChecked
      
    })
  },
  handleNum(event) {
    //通过id值，找到数组中对应的项目，将项目中的producount
    console.log(event.detail)
    var carts = this.data.carts
    var { aid } = event.currentTarget.dataset;
    carts.forEach(item => {
      if (item.id == aid) [
        item.productCount = event.detail
      ]
    })
    this.setData({
      carts
    })
    this.handleSum()
  },
  handleSelect(event) {
    console.log(event.detail)
    var carts = this.data.carts
    var { aid } = event.currentTarget.dataset;
    carts.forEach(item => {
      if (item.id == aid) [
        item.isSelected = event.detail
      ]
    })
    var allChecked = carts.every(item => {
      return item.isSelected
    })
    this.setData({
      carts,
      allChecked
    })
    this.handleSum()
  },
  handleAll(event) {
    console.log(event.detail)
    var carts = this.data.carts
    carts.forEach(item => {
      item.isSelected = event.detail
    })
    this.setData({
      allChecked: event.detail,
      carts
    })
    this.handleSum()
  },
  handleSum() {
    var sum = 0
    var carts = this.data.carts
    carts.forEach(item => {
      if (item.isSelected) {
        sum += (item.productCount) * (item.productPrice)
      }
    })
    this.setData({
      sum:sum*100
    })
  }
})